<!-- 添加患者页面 -->
<template>
  <TopNavigation leftText="添加患者" rightText="" />
  <view>
    <wd-form ref="form" :model="model">
      <wd-cell-group border>
        <wd-input
          v-model="model.value1"
          label="姓名"
          label-width="100px"
          prop="value1"
          clearable
          placeholder="请输入患者姓名"
          :rules="[{ required: true, message: '请填写患者名' }]"
        />
        <wd-input
          v-model="model.value2"
          label="身份证号"
          label-width="100px"
          prop="value2"
          clearable
          placeholder="请输入身份证号"
          :rules="[
            { required: true, message: '请填写身份证号' },
            {
              required: false,
              pattern:
                /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i,
              message: '请填写正确的身份证号',
            },
          ]"
        />
      </wd-cell-group>
      <view
        style="
          display: flex;
          align-items: center;
          justify-content: space-between;
          width: 100%;
          padding: 10rpx 0;
          background-color: #fff;
          border-top: 1px solid #f1f1f1;
        "
      >
        <text style="margin-left: 35rpx; font-size: 28rpx">性别</text>
        <view style="margin-right: 35rpx">
          <wd-radio-group v-model="valueA" inline checked-color="#00c8ab" shape="dot">
            <wd-radio value="男">男</wd-radio>
            <wd-radio value="女">女</wd-radio>
          </wd-radio-group>
        </view>
      </view>
      <view
        style="
          display: flex;
          align-items: center;
          justify-content: space-between;
          width: 100%;
          padding: 30rpx 0;
          background-color: #fff;
          border-top: 1px solid #f1f1f1;
        "
      >
        <text style="margin-left: 35rpx; font-size: 28rpx">设为默认就诊人</text>
        <view style="margin-right: 35rpx">
          <wd-checkbox v-model="valueB" checked-color="#00c8ab"></wd-checkbox>
        </view>
      </view>
    </wd-form>
    <view class="patieBut">
      <wd-button type="success" class="w-85%" @click="handleSubmit">保存并选择</wd-button>
    </view>
    <wd-toast />
  </view>
</template>

<script setup lang="ts">
import TopNavigation from "@/components/TopNavigation.vue";
import { useToast } from "wot-design-uni";
import { LoginPinia } from "@/store/modules/Login";
const loginValue = LoginPinia();
const toast = useToast();
const { success: showSuccess } = useToast();
//患者性别
const valueA = ref<string>("男");
//是否为默认就诊人
const valueB = ref<boolean>(false);
const model = reactive<{
  value1: string;
  value2: string;
}>({
  value1: "",
  value2: "",
});

const form = ref();
//通过身份证号获取年龄
function getAgeFromIDCard(idCard: string): number | null {
  // 提取出生日期部分（第7到14位）
  const birthDateStr = idCard.substring(6, 14);
  const birthYear = parseInt(birthDateStr.substring(0, 4), 10);
  const birthMonth = parseInt(birthDateStr.substring(4, 6), 10);
  const birthDay = parseInt(birthDateStr.substring(6, 8), 10);

  // 获取当前日期
  const today = new Date();
  const currentYear = today.getFullYear();
  const currentMonth = today.getMonth() + 1; // getMonth() 返回的是 0-11
  const currentDay = today.getDate();

  // 计算年龄
  let age = currentYear - birthYear;
  if (currentMonth < birthMonth || (currentMonth === birthMonth && currentDay < birthDay)) {
    age--; // 如果还没过生日，则年龄减1
  }

  return age;
}

//添加患者
function handleSubmit() {
  form.value
    .validate()
    .then(({ valid, errors }) => {
      if (valid) {
        for (let i = 0; i <= loginValue.ManagePatients.length; i++) {
          if (
            model.value1 != loginValue.ManagePatients[i].name &&
            model.value2 != loginValue.ManagePatients[i].identity &&
            i + 1 == loginValue.ManagePatients.length
          ) {
            if (valueB.value) {
              const obj = {
                name: model.value1,
                sex: valueA.value,
                age: getAgeFromIDCard(model.value2),
                identity: model.value2,
              };
              loginValue.addManagePatients(obj);
              loginValue.changeDefault(loginValue.ManagePatients.length - 1);
              uni.navigateBack({ delta: 1 });
            } else {
              const obj = {
                name: model.value1,
                sex: valueA.value,
                age: getAgeFromIDCard(model.value2),
                identity: model.value2,
              };
              loginValue.addManagePatients(obj);
              uni.navigateBack({ delta: 1 });
            }
          } else {
            toast.error("用户已存在");
          }
        }
      }
    })
    .catch((error) => {
      console.log(error, "error");
    });
}
</script>

<style lang="scss" scoped>
.footer {
  padding: 12px;
}
.patieBut {
  position: fixed;
  bottom: 0;
  display: flex;
  justify-content: center;
  width: 100%;
  padding: 15rpx 0;
}
</style>
